/*******************************************************************************
 * Copyright 2011 Towee.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

package net.towee.server.rpc.servlet;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.towee.server.CoreSettings;
import net.towee.server.authentication.SessionAuthManager;
import net.towee.server.gxp.ToweeClientPage;

import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.inject.name.Named;

/**
 * The HTTP servlet for serving a towee client along with content generated on
 * the server.
 */
public class ToweeClientServlet extends HttpServlet {

	private final String domain;
	private final SessionAuthManager sessionManager;
	private final int port;

	/**
	 * Creates a servlet for the wave client.
	 */
	@Inject
	public ToweeClientServlet(
			@Named(CoreSettings.TOWEE_SERVER_DOMAIN) String domain,
			@Named(CoreSettings.TOWEE_SERVER_PORT) int port,
			SessionAuthManager sessionManager) {
		
		this.domain = domain;
		this.port = port;
		this.sessionManager = sessionManager;
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
			response.setContentType("text/html;charset=UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);

			// Get user ID for auth checking
			String cookieId = null;
			for(Cookie c : request.getCookies()) {
				if(c.getName().equals("__towee_rem_id")) {
					cookieId = c.getValue();
				}
			}
			String id = sessionManager.getLoggedInUser(request.getSession(), cookieId);
			
			// If user not logged in
			if (id == null) {
				response.addCookie(new Cookie("__towee_rem_id", ""));
				response.sendRedirect("/auth");
				return;
			}

			try {
				ToweeClientPage.write(response.getWriter(), new GxpContext(
						request.getLocale()), "ru");
			} catch (IOException e) {
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				return;
			}
		}
}
